package com.huahai.security.core.validate.code;

import com.huahai.security.core.exception.ValidateCodeException;
import com.huahai.security.core.properties.StatusCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: Jun
 * @Date: 2020/7/17
 *
 * 验证码处理器持有者
 */
@Component
public class ValidateCodeProcessorHolder {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 得到所有的验证码处理器实现类
     */
    @Autowired
    private Map<String, ValidateCodeProcessor> validateCodeProcessors;

    public ValidateCodeProcessor findValidateCodeProcessor(ValidateCodeType type) {
        return findValidateCodeProcessor(type.toString().toLowerCase());
    }

    /**
     * 根据验证码里类型得到 对应的验证码处理器
     * @param type
     * @return
     */
    public ValidateCodeProcessor findValidateCodeProcessor(String type) {
        String name = type.toLowerCase() + ValidateCodeProcessor.class.getSimpleName();
        ValidateCodeProcessor processor = validateCodeProcessors.get(name);
        if (processor == null) {
            logger.error("验证码处理器" + name + "不存在");
            throw new ValidateCodeException(StatusCodeEnum.HSC400007.getCode(),StatusCodeEnum.HSC400007.getMessage());
        }
        return processor;
    }

}
